<?php

	include_once('model/User.php');
	include_once('model/Role.php');
	include_once('db/config.php');
	
	function getUsername()
	{
		$username = "";
		if(isset($_SESSION['username']))
		{
			$username = $_SESSION['username'];
		}
		return $username;
	}
	
	function isLoggedIn()
	{
		$loggedIn = false;
		
		try
		{
			$sessionUsername = '';
			
			if(isset($_SESSION['username']) && isset($_SESSION['logintime']))
			{
				$sessionUsername = $_SESSION['username'];
			}
			if(empty($sessionUsername))
			{	
				$loggedIn = false;
			}
			else
			{
				$loggedIn = true;
			}
		}
		catch(Exception $ex)
		{
			throw new Exception($ex->getMessage());
		}
		
		return $loggedIn;
	}
	
	function loginUser($username, $password)
	{
		$result = false;
		try
		{
			connectDb("tictocwatches");
			global $dbLink;
			
			$queryString = "call sp_IsUserLoginValid('".mysqli_real_escape_string($dbLink,$username)."','".md5(mysqli_real_escape_string($dbLink,$password))."')";
			//print_r($queryString);
			
			$resultPointer = mysqli_query($dbLink,$queryString);
			
			if($resultPointer)
			{
				while($resultRow = mysqli_fetch_assoc($resultPointer))
				{
					$resultSet = $resultRow;
					
					if( $resultSet["result"] == "VALID")
					{
						$result = true;	
					}
					else
					{
						$result = false;
					}
				}
			}
			else
			{
				$queryError = mysqli_errno($dbLink);
				//print_r($queryError);
				if($queryError!=0)
				{
					parseDatabaseError($queryError);
				}
				$result = false;
			}
		}
		catch(Exception $ex)
		{
			throw new Exception($ex->getMessage());
		}
		
		return $result;
	}
	
	function retrieveUser($username)
	{
		$foundUser = null;
		try
		{
			connectDb("tictocwatches");
			global $dbLink;
			$resultPointer = mysqli_query($dbLink,"call sp_getUser('".mysqli_real_escape_string($dbLink,$username)."')");
			
			if($resultPointer)
			{
				while($resultRow = mysqli_fetch_array($resultPointer))
				{
					$foundUser = new User();
					$foundUser->id = $resultRow["user_id"];
					$foundUser->username = $resultRow["username"];	
					$foundUser->firstName = $resultRow["first_name"];		
					$foundUser->lastName = $resultRow["last_name"];		
					$foundUser->emailAddress = $resultRow["email_address"];	
					$foundUser->password = $resultRow["password"];	
					$foundUser->gender = $resultRow["gender"];	
					
					if(!is_null($resultRow["profile_img_filename"]))
					{
						$foundUser->profileImgFilename = $resultRow["profile_img_filename"];
					}

					if(!is_null($resultRow["mobile_contact"]))
					{
						$foundUser->mobileContact = $resultRow["mobile_contact"];
					}
					if(!is_null($resultRow["home_contact"]))
					{
						$foundUser->homeContact = $resultRow["home_contact"];
					}
					if(!is_null($resultRow["residence_address"]))
					{
						$foundUser->residenceAddress = $resultRow["residence_address"];
					}
					if(!is_null($resultRow["mailing_address"]))
					{
						$foundUser->mailingAddress = $resultRow["mailing_address"];
					}
					if(!is_null($resultRow["about_me"]))
					{
						$foundUser->aboutMe = $resultRow["about_me"];
					}

					$foundUser->occupation = '';
					
					
					if(!is_null($resultRow["role_id"]))
					{
						$foundUser->roles = new Role();
						$foundUser->roles->roleID = $resultRow["role_id"];	
						$foundUser->roles->name = $resultRow["role_name"];	
						$foundUser->roles->description = $resultRow["role_description"];
					}
				}
			}
		}
		catch(Exception $ex)
		{
			throw new Exception($ex->getMessage());
		}
		return $foundUser;
	}
	
	function retrieveUserByID($userID)
	{
		$foundUser = null;
		try
		{
			connectDb("tictocwatches");
			global $dbLink;
			$resultPointer = mysqli_query($dbLink,"call sp_getUserByID('".mysqli_real_escape_string($dbLink,$userID)."')");
			if($resultPointer)
			{
				while($resultRow = mysqli_fetch_array($resultPointer))
				{
					$foundUser = new User();
					$foundUser->id = $resultRow["user_id"];
					$foundUser->username = $resultRow["username"];	
					$foundUser->firstName = $resultRow["first_name"];		
					$foundUser->lastName = $resultRow["last_name"];		
					$foundUser->emailAddress = $resultRow["email_address"];	
					$foundUser->password = $resultRow["password"];	
					$foundUser->gender = $resultRow["gender"];	
					if(!is_null($resultRow["profile_img_filename"]))
					{
						$foundUser->profileImgFilename = $resultRow["profile_img_filename"];
					}
					
					if(!is_null($resultRow["mobile_contact"]))
					{
						$foundUser->mobileContact = $resultRow["mobile_contact"];
					}
					if(!is_null($resultRow["mobile_number"]))
					{
						$foundUser->mobileContactNumber = $resultRow["mobile_number"];
					}
					
					if(!is_null($resultRow["home_contact"]))
					{
						$foundUser->homeContact = $resultRow["home_contact"];			
					}
					if(!is_null($resultRow["home_number"]))
					{
						$foundUser->homeContactNumber = $resultRow["home_number"];	
					}
					
					if(!is_null($resultRow["residence_address"]))
					{
						$foundUser->residenceAddress = $resultRow["residence_address"];
					}
					
					if(!is_null($resultRow["mailing_address"]))
					{
						$foundUser->mailingAddress = $resultRow["mailing_address"];
					}
					if(!is_null($resultRow["mailing_street1"]))
					{
						$foundUser->mailingStreet1 = $resultRow["mailing_street1"];
					}
					if(!is_null($resultRow["mailing_street2"]))
					{
						$foundUser->mailingStreet2 = $resultRow["mailing_street2"];
					}
					if(!is_null($resultRow["mailing_city"]))
					{
						$foundUser->mailingCity = $resultRow["mailing_city"];
					}
					if(!is_null($resultRow["mailing_country_id"]))
					{
						$foundUser->mailingCountry = $resultRow["mailing_country_id"];
					}
					
					if(!is_null($resultRow["about_me"]))
					{
						$foundUser->aboutMe = $resultRow["about_me"];
					}
					/*				
					u.user_id,
					u.username,
					u.first_name,
					u.last_name,
					u.email_address,
					u.password,
					u.gender,
					u.about_me,
					u.mobile_contact,
					mc.number AS mobile_number,
					u.home_contact,
					hc.number AS home_number,
					u.residence_address,
					u.mailing_address,
					ma.street1 AS mailing_street1,
					ma.street2 AS mailing_street2,
					ma.city AS mailing_city,
					ma.country_id AS mailing_country_id,
					ma.province AS mailing_province,
					u.profile_img_filename,*/
					
					if(!is_null($resultRow["role_id"]))
					{
						$foundUser->roles = new Role();
						$foundUser->roles->roleID = $resultRow["role_id"];	
						$foundUser->roles->name = $resultRow["role_name"];	
						$foundUser->roles->description = $resultRow["role_description"];
					}
					
					//print_r($foundUser);
				}
			}
		}
		catch(Exception $ex)
		{
			throw new Exception($ex->getMessage());
		}
		return $foundUser;
	}
	
	function registerUser(
		$username,
		$firstName,
		$lastName,
		$emailAddress,
		$password,
		$aboutMe,
		$gender,

		$residenceStreet1,
		$residenceStreet2,
		$residenceCountry,
		$residenceCity,
		$residenceProvince,

		$mailingStreet1,
		$mailingStreet2,
		$mailingCountry,
		$mailingCity,
		$mailingProvince,

		$homeCountryCode,
		$homeAreaCode,
		$homeNumber,

		$mobileCountryCode,
		$mobileAreaCode,
		$mobileNumber,
		
		$userRole,
		
		$profileImgFilename
	)
	{
		$result = false;
		$resultSet = null;
		
		try
		{
			connectDb("tictocwatches");
			global $dbLink;
			/*
				IN username VARCHAR(25),
				IN first_name VARCHAR(45),
				IN last_name VARCHAR(45),
				IN email_address VARCHAR(255),
				IN `password` VARCHAR(128),
				IN about_me VARCHAR(255),
				IN gender VARCHAR(1),

				IN residence_street1 VARCHAR(100),
				IN residence_street2 VARCHAR(100),
				IN residence_country_id INT,
				IN residence_city VARCHAR(100),
				IN residence_province VARCHAR(100),

				IN mailing_street1 VARCHAR(100),
				IN mailing_street2 VARCHAR(100),
				IN mailing_country_id INT,
				IN mailing_city VARCHAR(100),
				IN mailing_province VARCHAR(100),

				IN home_country_code VARCHAR(10),
				IN home_area_code VARCHAR(10),
				IN `home_number` VARCHAR(20),

				IN mobile_country_code VARCHAR(10),
				IN mobile_area_code VARCHAR(10),
				IN `mobile_number` VARCHAR(20)
			*/
			$queryString = "call sp_RegisterUser('".mysqli_real_escape_string($dbLink,$username)."','".mysqli_real_escape_string($dbLink,$firstName)."','".mysqli_real_escape_string($dbLink,$lastName)."','".mysqli_real_escape_string($dbLink,$emailAddress)."','".md5(mysqli_real_escape_string($dbLink,$password))."','".mysqli_real_escape_string($dbLink,$aboutMe)."','".mysqli_real_escape_string($dbLink,$gender)."','".mysqli_real_escape_string($dbLink,$residenceStreet1)."','".mysqli_real_escape_string($dbLink,$residenceStreet2)."',".mysqli_real_escape_string($dbLink,$residenceCountry).",'".mysqli_real_escape_string($dbLink,$residenceCity)."','".mysqli_real_escape_string($dbLink,$residenceProvince)."','".mysqli_real_escape_string($dbLink,$mailingStreet1)."','".mysqli_real_escape_string($dbLink,$mailingStreet2)."',".mysqli_real_escape_string($dbLink,$mailingCountry).",'".mysqli_real_escape_string($dbLink,$mailingCity)."','".mysqli_real_escape_string($dbLink,$mailingProvince)."','".mysqli_real_escape_string($dbLink,$homeCountryCode)."','".mysqli_real_escape_string($dbLink,$homeAreaCode)."','".mysqli_real_escape_string($dbLink,$homeNumber)."','".mysqli_real_escape_string($dbLink,$mobileCountryCode)."','".mysqli_real_escape_string($dbLink,$mobileAreaCode)."','".mysqli_real_escape_string($dbLink,$mobileNumber)."',".mysqli_real_escape_string($dbLink,$userRole).",'".mysqli_real_escape_string($dbLink,$profileImgFilename)."')";
			print_r($queryString);
			
			$resultPointer = mysqli_query($dbLink,$queryString);
			
			if($resultPointer)
			{
				while($resultRow = mysqli_fetch_assoc($resultPointer))
				{
					$resultSet = $resultRow;
					
					if( $resultSet["state"] == "SUCCESS")
					{
						$result = true;	
					}
					else
					{
						$result = false;
					}
				}
				print_r($resultSet["state"]);
			}
			else
			{
				$queryError = mysqli_errno($dbLink);
				//print_r($queryError);
				if($queryError!=0)
				{
					parseDatabaseError($queryError);
				}
				$result = false;
			}
		}
		catch(Exception $ex)
		{
			throw new Exception($ex->getMessage());
		}
		return $result;
	}
	
	function updateUser(
	
		$updateUserID,
		$updateFirstName,
		$updateLastName,
		$updateEmailAddress,
		$updateAboutMe,
		$updateGender,
		
		$updateMailingAddressID,
		$updateStreet1,
		$updateStreet2,
		$updateCountry,
		$updateCity,

		$updateHomeContactID,
		$updateHomeContactNumber,
		
		$updateMobileContactID,
		$updateMobileContactNumber,

		$newFileName
	)
	{
		$result = false;
		$resultSet = null;
		
		try
		{
			connectDb("tictocwatches");
			global $dbLink;
			$queryString = "call sp_UpdateUserProfile(".mysqli_real_escape_string($dbLink,$updateUserID).",'".mysqli_real_escape_string($dbLink,$updateFirstName)."','".mysqli_real_escape_string($dbLink,$updateLastName)."','".mysqli_real_escape_string($dbLink,$updateEmailAddress)."','".mysqli_real_escape_string($dbLink,$updateAboutMe)."','".mysqli_real_escape_string($dbLink,$updateGender)."',".mysqli_real_escape_string($dbLink,$updateMailingAddressID).",'".mysqli_real_escape_string($dbLink,$updateStreet1)."','".mysqli_real_escape_string($dbLink,$updateStreet2)."','".mysqli_real_escape_string($dbLink,$updateCity)."',".mysqli_real_escape_string($dbLink,$updateCountry).",".mysqli_real_escape_string($dbLink,$updateHomeContactID).",'".mysqli_real_escape_string($dbLink,$updateHomeContactNumber)."',".mysqli_real_escape_string($dbLink,$updateMobileContactID).",'".mysqli_real_escape_string($dbLink,$updateMobileContactNumber)."','".mysqli_real_escape_string($dbLink,$newFileName)."')";
			//print_r($queryString);
			
			$resultPointer = mysqli_query($dbLink,$queryString);
			
			if($resultPointer)
			{
				while($resultRow = mysqli_fetch_assoc($resultPointer))
				{
					$resultSet = $resultRow;
					
					if( $resultSet["state"] == "SUCCESS")
					{
						$result = true;	
					}
					else
					{
						$result = false;
					}
				}
				//print_r($resultSet["state"]);
			}
			else
			{
				$queryError = mysqli_errno($dbLink);
				//print_r($queryError);
				if($queryError!=0)
				{
					parseDatabaseError($queryError);
				}
				$result = false;
			}
		}
		catch(Exception $ex)
		{
			throw new Exception($ex->getMessage());
		}
		return $result;
	}
	
	function parseDatabaseError($errorCode)
	{
		switch($errorCode)
		{
			case 1032:
				throw new Exception("User account cannot be found. ");
			break;
			case 1452:
				throw new Exception("This user account does not exist.");
			break;
			case 1169:
				throw new Exception("This user account already exist exist.");
			break;
			
		}
	}
?>